import axios from 'axios'
import { ElNotification , ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from '@/utils/xpp'
import cache from '@/plugins/cache'
import moment from 'moment';
import useUserStore from '@/store/modules/user'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const xirService = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_XIR_API,
  // 超时
  timeout: 180000
})
const userStore = useUserStore()
// request拦截器
xirService.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    }
    const sessionObj = cache.session.getJSON('sessionObj')
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      cache.session.setJSON('sessionObj', requestObj)
    } else {
      const s_url = sessionObj.url;                // 请求地址
      const s_data = sessionObj.data;              // 请求数据
      const s_time = sessionObj.time;              // 请求时间
      const interval = 1000;                       // 间隔时间(ms)，小于此时间视为重复提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
        const message = '数据正在处理，请勿重复提交';
        console.warn(`[${s_url}]: ` + message)
        return Promise.reject(new Error(message))
      } else {
        cache.session.setJSON('sessionObj', requestObj)
      }
    }
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
xirService.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if(res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
      return res.data
    }
    if (code === 500) {
      ElMessage({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      ElNotification.error({
        title: msg
      })
      return Promise.reject('error')
    } else {
      return  Promise.resolve(res.data)
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)


export function buildXirJson(tradeForm){
  var productType =tradeForm.calcInstrumentForm.productType;
  var trdType = tradeForm.calcInstrumentForm.payDirection == '1' ? "1010" : "1011";
  if(trdType != tradeForm.trdType){
    tradeForm.trdType = trdType;
  }
  var resultJson = buildXirJsonBase(tradeForm);
  switch (productType){
    case "Vanilla":
      resultJson =  buildXirJsonVanilla(tradeForm,resultJson);
      break;
    case "Digital":
      resultJson =  buildXirJsonDigital(tradeForm,resultJson);
      break;
    case "Barrier":
      resultJson = buildXirJsonBarrier(tradeForm,resultJson);
      break;
    default:
      return "noProductType";
  }
  return resultJson;
}

function buildXirJsonBase(tradeForm){
  return {
    "Header":{
      "Serial_No":moment(new Date()).format('YYYYMMDD HH:mm:ss.SSS'),   //报文流水号
      "Timestmp":moment(new Date()).format('YYYYMMDD HH:mm:ss.SSS'),  //时间戳
      "Ext_No":tradeForm.extTradeId,  //外部成交编号
      "User": userStore.userInfo.uuid,  //用户ID
      "Action":"2101",  //接口功能号
      "Requestsysname":"600918"  //交易信息来源
    },
    "Record":{
      "BaseInfo":{
        "Secu_Int":tradeForm.accId,  //期权内帐账户
        "Party_Name":tradeForm.partyName,  //交易对手全称
        "TRADER_ID":tradeForm.trader,    //投资经理
        "TrdType":tradeForm.trdType,  //期权交易方向
        "OrdDate":tradeForm.tradeDate,   //期权交易日
        //"IntentionDate":"2021-11-05"  //期权意向日
      },
      "OTHERINFO":{
        "MEMO":tradeForm.remark  //备注信息
      }
    }
  };
}


function buildXirJsonVanilla(tradeForm,resultJson){
  resultJson.Record.OptionTrade = {
    "CashFlowSettleType":tradeForm.cashFlowSettleType,//结算方式,CPAS为对手资金户，DIRECT为直接划付
    // "EXT_Cash":"0.035",  //公司给部门的利润
    "Premium":[
      {
        "PaymentDate":tradeForm.tequityStructure.isPayOnExpire == 1 ? "" : tradeForm.tequityStructure.feeDate,   //期权费支付日期，为空认为到期轧差
        //手数报价传单价，本金报价传期权费率
        "PaymentAmountRate":tradeForm.calcInstrumentForm.quotationType == 'notional' ? (tradeForm.tequityStructure.feeRate / 100).toString() : tradeForm.tequityStructure.unitPrice, //期权费比例 期权费=本金*年化系数*参与率（OptionLegs中第一个的参与率）*期权费比例
        "IfAnnual":tradeForm.tequityStructure.feeYear   //是否年化1年化，0非年化，默认非年化(如果年化，年化系数使用OptionLegs中第一个的计息基准和term)
      }
    ],
    "OptionLegs":[
      {
        "ProductType":"VANILLA",   //期权品种
        // "ProductType_EXT":"1",  //外部对接期权品种
        "CalcNpv":"1",  //是否计算估值，默认1，计算估值，0不计算估值
        "QuoteType": tradeForm.calcInstrumentForm.quotationType == 'notional' ? "1" : "0",//报价方式  0 数量，1 本金，默认按本金
        "LegData":{
          "TrdType":tradeForm.trdType,   //期权方向
          "UnderlyerId":tradeForm.calcInstrumentForm.instrumentId.split(",")[0] + '.' + tradeForm.calcInstrumentForm.instrumentId.split(",")[2],  //标的代码
          "EffectiveDate":tradeForm.calcInstrumentForm.effectiveDate,   //期权起始日
          "TerminationDate":tradeForm.calcInstrumentForm.terminationDate,   //期权到期日
          "SettlementDateOffset":tradeForm.calcInstrumentForm.paymentDaysOffset.toString(),  //期权结算偏移
          "FixingDate":tradeForm.calcInstrumentForm.terminationDate,   //期权定盘日
          "Notional":tradeForm.calcInstrumentForm.notional.toString(),   //本金单位 元
          "OrdCount": tradeForm.calcInstrumentForm.optionEntitlement.toString(),//数量·(数量报价)
          "Term":tradeForm.calcInstrumentForm.term.toString(),  //期权合约期限，默认不填写=到期日-起始日
          "SpotPrice":tradeForm.calcInstrumentForm.spotPrice,  //标的起初价格
          "OptionType":tradeForm.calcInstrumentForm.optionType,   //Call/Put
          "StrikeRate":(tradeForm.calcInstrumentForm.strikePercentage / 100).toString(),   //行权价比例
          "IfAnnual":tradeForm.calcInstrumentForm.moneynessOption,    //是否年化1年化，0非年化，默认非年化
          "DayCounter":dayCounterTranslate(tradeForm.calcInstrumentForm.daycounter),  //计息基准，IfAnnual=1，不填写默认A/365
          "ParticipationRate":(tradeForm.calcInstrumentForm.participationRate / 100).toString()  //期权参与率
        }
      }
    ]
  };
  return resultJson;
}


function buildXirJsonDigital(tradeForm,resultJson){
  resultJson.Record.OptionTrade = {
    "CashFlowSettleType":tradeForm.cashFlowSettleType,//结算方式,CPAS为对手资金户，DIRECT为直接划付
    // "EXT_Cash":"0.035",  //公司给部门的利润
    "Premium":[
      {
        "PaymentDate":tradeForm.tequityStructure.isPayOnExpire == 1 ? "" : tradeForm.tequityStructure.feeDate,   //期权费支付日期，为空认为到期轧差
        "PaymentAmountRate":tradeForm.calcInstrumentForm.quotationType == 'notional' ? (tradeForm.tequityStructure.feeRate / 100).toString() : tradeForm.tequityStructure.unitPrice, //期权费比例 期权费=本金*年化系数*参与率（OptionLegs中第一个的参与率）*期权费比例
        "IfAnnual":tradeForm.tequityStructure.feeYear   //是否年化1年化，0非年化，默认非年化(如果年化，年化系数使用OptionLegs中第一个的计息基准和term)
      }
    ],
    "OptionLegs":[
      {
        "ProductType":"DIGITAL",   //期权品种
        // "ProductType_EXT":"11",  //外部对接期权品种
        "CalcNpv":"1",  //是否计算估值，默认1，计算估值，0不计算估值
        "QuoteType": tradeForm.calcInstrumentForm.quotationType == 'notional' ? "1" : "0",//报价方式  0 数量，1 本金，默认按本金
        "LegData":{
          "TrdType":tradeForm.trdType,   //期权方向
          "UnderlyerId":tradeForm.calcInstrumentForm.instrumentId.split(",")[0] + '.' + tradeForm.calcInstrumentForm.instrumentId.split(",")[2],  //期权标的
          "EffectiveDate":tradeForm.calcInstrumentForm.effectiveDate,   //期权起始日
          "TerminationDate":tradeForm.calcInstrumentForm.terminationDate,   //期权到期日
          "SettlementDateOffset":tradeForm.calcInstrumentForm.paymentDaysOffset.toString(),  //期权结算偏移
          "FixingDate":tradeForm.calcInstrumentForm.terminationDate,   //期权定盘日
          "Notional":tradeForm.calcInstrumentForm.notional.toString(),   //本金单位 元
          "OrdCount": tradeForm.calcInstrumentForm.optionEntitlement.toString(),//数量·(数量报价)
          "Term":tradeForm.calcInstrumentForm.term.toString(),  //期权合约期限，默认不填写=到期日-起始日
          "SpotPrice":tradeForm.calcInstrumentForm.spotPrice,  //标的起初价格
          "OptionType":tradeForm.calcInstrumentForm.optionType,   //Call/Put
          "StrikeRate":(tradeForm.calcInstrumentForm.strikePercentage / 100).toString(),   //行权价比例
          "StrikeInclude":tradeForm.calcInstrumentForm.moneynessOption,   //行权价是否包含 0 不包含，1 包含，默认 为0
          "IfAnnual":tradeForm.calcInstrumentForm.moneynessOption,    //是否年化1年化，0非年化，默认非年化
          "DayCounter":dayCounterTranslate(tradeForm.calcInstrumentForm.daycounter),  //计息基准，IfAnnual=1，不填写默认A/365
          "RebateRate": tradeForm.calcInstrumentForm.quotationType == 'notional' ? (tradeForm.calcInstrumentForm.paymentAmountPecentage / 100).toString() : tradeForm.calcInstrumentForm.unitPaymentAmount,  //补偿收益率
          "ParticipationRate":(tradeForm.calcInstrumentForm.participationRate / 100).toString()  //期权参与率
        }
      }
    ]
  };
  return resultJson;
}



function buildXirJsonBarrier(tradeForm,resultJson){
  resultJson.Record.OptionTrade = {
    "CashFlowSettleType":tradeForm.cashFlowSettleType,//结算方式,CPAS为对手资金户，DIRECT为直接划付
    "EXT_Cash":"0.035",  //公司给部门的利润
    "Premium":[
      {
        "PaymentDate":tradeForm.tequityStructure.isPayOnExpire == 1 ? "" : tradeForm.tequityStructure.feeDate,   //期权费支付日期，为空认为到期轧差
        "PaymentAmountRate":(tradeForm.tequityStructure.feeRate / 100).toString(), //期权费比例 期权费=本金*年化系数*参与率（OptionLegs中第一个的参与率）*期权费比例
        "IfAnnual":tradeForm.tequityStructure.feeYear   //是否年化1年化，0非年化，默认非年化(如果年化，年化系数使用OptionLegs中第一个的计息基准和term)
      }
    ],
    "OptionLegs":[
      {
        "ProductType":"Barrier",   //期权品种
        "ProductType_EXT":"11",  //外部对接期权品种
        "CalcNpv":"1",  //是否计算估值，默认1，计算估值，0不计算估值
        "LegData":{
          "TrdType":tradeForm.trdType,   //期权方向
          "UnderlyerId":tradeForm.calcInstrumentForm.instrumentId.split(",")[0] + '.' + tradeForm.calcInstrumentForm.instrumentId.split(",")[2],  //期权标的
          "EffectiveDate":tradeForm.calcInstrumentForm.effectiveDate,   //期权起始日
          "TerminationDate":tradeForm.calcInstrumentForm.terminationDate,   //期权到期日
          "SettlementDateOffset":tradeForm.calcInstrumentForm.paymentDaysOffset.toString(),  //期权结算偏移
          "FixingDate":tradeForm.calcInstrumentForm.terminationDate,   //期权定盘日
          "Notional":tradeForm.calcInstrumentForm.notional.toString(),   //本金单位 元
          "Term":tradeForm.calcInstrumentForm.term.toString(),  //期权合约期限，默认不填写=到期日-起始日
          "SpotPrice":tradeForm.calcInstrumentForm.spotPrice,  //标的起初价格
          "OptionType":tradeForm.calcInstrumentForm.optionType,   //Call/Put
          "StrikeRate":(tradeForm.calcInstrumentForm.strikePercentage / 100).toString(),   //行权价比例
          "StrikeInclude":tradeForm.calcInstrumentForm.moneynessOption,   //行权价是否包含 0 不包含，1 包含，默认 为0
          "IfAnnual":tradeForm.calcInstrumentForm.moneynessOption,    //是否年化1年化，0非年化，默认非年化
          "DayCounter":dayCounterTranslate(tradeForm.calcInstrumentForm.daycounter),  //计息基准，IfAnnual=1，不填写默认A/365
          "RebateRate":"0",  //补偿收益率
          "ParticipationRate":(tradeForm.calcInstrumentForm.participationRate / 100).toString()  //期权参与率
        }
      }
    ]
  };
  return resultJson;
}


function dayCounterTranslate(dayCounter){
  switch (dayCounter){
    case "Actual/360":
        return "A/360";
    case "Actual/365 (Fixed)":
        return "A/365";
    default:
        return "A/365";
  }
}




export default xirService
